<template>
  <div class="payment-page">
    <el-container>
      <el-main>
        <!-- 页面标题 -->
        <div class="page-header">
          <h1 class="page-title">订单支付</h1>
          <p class="page-subtitle">请选择支付方式完成订单</p>
        </div>

        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>

        <div v-else-if="!order" class="empty-container">
          <el-empty description="订单信息不存在" />
        </div>

        <div v-else class="payment-content">
          <!-- 订单信息 -->
          <el-card class="order-info-card">
            <template #header>
              <span>订单信息</span>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单号">
                {{ order.orderSn }}
              </el-descriptions-item>
              <el-descriptions-item label="订单金额">
                <span class="amount">¥{{ order.totalAmount }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="商品数量">
                {{ getTotalQuantity(order.orderItems || []) }} 件
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                {{ formatDate(order.createdAt) }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 支付方式选择 -->
          <el-card class="payment-method-card">
            <template #header>
              <span>选择支付方式</span>
            </template>
            <div class="payment-methods">
              <el-radio-group v-model="selectedPaymentMethod">
                <div class="payment-method-item">
                  <el-radio value="alipay">
                    <div class="payment-method-content">
                      <div class="payment-logo alipay">支付宝</div>
                      <span>支付宝</span>
                    </div>
                  </el-radio>
                </div>
                <div class="payment-method-item">
                  <el-radio value="wechat">
                    <div class="payment-method-content">
                      <div class="payment-logo wechat">微信</div>
                      <span>微信支付</span>
                    </div>
                  </el-radio>
                </div>
                <div class="payment-method-item">
                  <el-radio value="unionpay">
                    <div class="payment-method-content">
                      <div class="payment-logo unionpay">银联</div>
                      <span>银联支付</span>
                    </div>
                  </el-radio>
                </div>
              </el-radio-group>
            </div>
          </el-card>

          <!-- 支付按钮 -->
          <el-card class="payment-action-card">
            <div class="payment-summary">
              <div class="payment-amount">
                <span class="amount-label">支付金额：</span>
                <span class="amount-value">¥{{ order.totalAmount }}</span>
              </div>
              <el-button
                type="primary"
                size="large"
                :loading="paying"
                @click="handlePayment"
                class="pay-button"
              >
                立即支付
              </el-button>
            </div>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineOptions } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderService, stockService } from '@/api'
import type { Order } from '@/types/order'
import type { OrderItem } from '@/types/order'
import { createLogger } from '@/utils/logger'

defineOptions({ name: 'PaymentPage' })

// Props - 支持路径参数和查询参数两种方式
interface Props {
  orderId?: string | number
}

const props = defineProps<Props>()
const route = useRoute()
const router = useRouter()

// 日志记录器
const paymentLogger = createLogger('Payment')

// 响应式数据
const order = ref<Order | null>(null)
const loading = ref(false)
const paying = ref(false)
const selectedPaymentMethod = ref('alipay')

// 获取订单ID的优雅方法
const getOrderId = (): string | number | null => {
  return props.orderId || route.params.orderId || route.query.orderId || null
}

// 方法
const fetchOrder = async () => {
  const orderId = getOrderId()
  if (!orderId) {
    ElMessage.error('订单ID不能为空')
    return
  }

  loading.value = true
  try {
    paymentLogger.info('获取订单详情:', { orderId })
    const response = await orderService.getOrderDetail(Number(orderId))
    order.value = response.data.data
    
    paymentLogger.info('订单详情加载成功:', { 
      orderSn: order.value?.orderSn,
      totalAmount: order.value?.totalAmount,
      payAmount: order.value?.payAmount 
    })
  } catch (error: any) {
    paymentLogger.error('获取订单信息失败:', error)
    ElMessage.error(error.message || '获取订单信息失败')
    // 如果订单不存在，跳转到订单列表
    setTimeout(() => {
      router.push('/orders')
    }, 2000)
  } finally {
    loading.value = false
  }
}

const getTotalQuantity = (items: OrderItem[]) => {
  return items.reduce((total, item) => total + item.quantity, 0)
}

const formatDate = (date: string | Date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

const handlePayment = async () => {
  if (!order.value) return

  // 确认支付操作
  try {
    await ElMessageBox.confirm(
      `确认支付 ¥${order.value.totalAmount} 吗？`,
      '确认支付',
      {
        confirmButtonText: '确认支付',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
  } catch {
    return // 用户取消支付
  }

  paying.value = true
  try {
            paymentLogger.info('开始模拟支付:', {
          orderId: order.value.orderId,
          orderNumber: order.value.orderNumber,
          amount: order.value.finalTotal,
          paymentMethod: selectedPaymentMethod.value
        })

    // 模拟支付过程（2-3秒）
    await new Promise((resolve) => setTimeout(resolve, 2000 + Math.random() * 1000))

    // 模拟支付成功（90%成功率）
    const success = Math.random() > 0.1
    
    if (success) {
      paymentLogger.info('模拟支付成功')
      ElMessage.success('支付成功！正在更新订单状态...')
      
      // 【重要】支付成功后更新订单状态为已支付
      // 状态码：0=待付款, 1=已支付, 2=已发货, 3=已完成, 4=已取消
      // ⚠️ 请勿删除此逻辑，否则订单状态不会更新
      try {
        await orderService.updateOrderStatus(order.value.orderId, 1) // 1=已支付
        paymentLogger.info('订单状态更新成功:', { 
          orderId: order.value.orderId, 
          newStatus: 1 
        })
        
        //库存修改内容修改位置发生改变，放在订单创建位置，并非支付界面

        // // 支付成功后，扣减本次订单涉及的SKU库存
        // try {
        //   // 按订单ID获取待扣减SKU清单
        //   const mapJson = sessionStorage.getItem('pendingOrderSkusMap')
        //   const orderKey = String(order.value.orderId)
        //   if (mapJson) {
        //     const map = JSON.parse(mapJson) as Record<string, Array<{ shoeId: number; sizeId: number; colorId: number; stockQuantity: number }>>
        //     const pending = map[orderKey] || []
        //     for (const sku of pending) {
        //       try {
        //         await stockService.decrease({ shoeId: sku.shoeId, sizeId: sku.sizeId, colorId: sku.colorId }, sku.stockQuantity)
        //       } catch (decErr) {
        //         paymentLogger.error('扣减库存失败:', { sku, error: decErr })
        //         // 单个SKU失败不阻断流程，可在后台对账
        //       }
        //     }
        //     // 扣减完成后清理该订单的挂起数据
        //     try {
        //       delete map[orderKey]
        //       sessionStorage.setItem('pendingOrderSkusMap', JSON.stringify(map))
        //     } catch {}
        //   }
        // } catch (invErr) {
        //   paymentLogger.error('库存扣减流程异常:', invErr)
        // }

        // 更新本地订单状态，避免页面刷新
        order.value.status = 1
        
        ElMessage.success('支付成功！正在跳转...')
      } catch (statusError: any) {
        paymentLogger.error('更新订单状态失败:', statusError)
        // 即使状态更新失败，也继续跳转，因为支付本身是成功的
        ElMessage.warning('支付成功，但状态更新异常，请刷新页面查看最新状态')
      }
      
      // 跳转到支付成功页面
      setTimeout(() => {
        router.push({
          path: '/payment/success',
          query: {
            orderId: order.value!.orderId.toString(),
            orderSn: order.value!.orderSn,
            amount: order.value!.payAmount.toString()
          }
        })
      }, 1000)
    } else {
      throw new Error('支付失败，请重试')
    }
  } catch (error: any) {
    paymentLogger.error('支付失败:', error)
    
    // 支付失败时，恢复已扣减的库存
    try {
      const pendingSkusJson = sessionStorage.getItem('pendingOrderSkusTemp')
      if (pendingSkusJson) {
        const pendingSkus = JSON.parse(pendingSkusJson) as Array<{
          shoeId: number
          sizeId: number
          colorId: number
          stockQuantity: number
        }>
        
        // 并发恢复所有SKU的库存
        await Promise.all(
          pendingSkus.map(async (sku) => {
            try {
              await stockService.increase(
                { shoeId: sku.shoeId, sizeId: sku.sizeId, colorId: sku.colorId },
                sku.stockQuantity
              )
              paymentLogger.info('库存恢复成功:', sku)
            } catch (restoreError) {
              paymentLogger.error('库存恢复失败:', { sku, error: restoreError })
              // 单个SKU恢复失败不阻断流程，可在后台对账
            }
          })
        )
        
        // 清理临时数据
        sessionStorage.removeItem('pendingOrderSkusTemp')
        paymentLogger.info('支付失败，库存已恢复')
      }
    } catch (restoreError) {
      paymentLogger.error('库存恢复流程异常:', restoreError)
    }
    
    ElMessage.error(error.message || '支付失败，请重试')
  } finally {
    paying.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchOrder()
})
</script>

<style scoped>
.payment-page {
  min-height: calc(100vh - 64px);
  background-color: #f8fafc;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.page-subtitle {
  font-size: 16px;
  color: #909399;
}

.loading-container {
  padding: 40px 0;
}

.empty-container {
  padding: 60px 0;
}

.payment-content {
  max-width: 800px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-info-card,
.payment-method-card,
.payment-action-card {
  margin-bottom: 0;
}

.amount {
  font-size: 18px;
  font-weight: 600;
  color: #e6a23c;
}

.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.payment-method-item {
  padding: 16px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  transition: border-color 0.2s;
}

.payment-method-item:hover {
  border-color: #409eff;
}

.payment-method-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.payment-logo {
  width: 32px;
  height: 32px;
  object-fit: contain;
}

.payment-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.payment-amount {
  display: flex;
  align-items: center;
  gap: 8px;
}

.amount-label {
  font-size: 16px;
  color: #606266;
}

.amount-value {
  font-size: 24px;
  font-weight: 600;
  color: #e6a23c;
}

.pay-button {
  min-width: 120px;
}

@media (max-width: 768px) {
  .payment-summary {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .pay-button {
    width: 100%;
  }
}
</style>
